import { ref, onMounted, onUnmounted, onBeforeUnmount } from 'vue'
import { useIntersectionObserver, useIntervalFn } from '@vueuse/core'
/**
 * 获取窗口滚动的位置
 * @returns x: 水平位置 y:垂直位置
 */
export function useWindowScroll () {
  const x = ref(0)
  const y = ref(0)
  const scrollFn = () => {
    x.value = document.documentElement.scrollLeft
    y.value = document.documentElement.scrollTop
  }
  onMounted(() => {
    window.addEventListener('scroll', scrollFn)
  })
  onUnmounted(() => {
    window.removeEventListener('scroll', scrollFn)
  })
  return {
    x,
    y
  }
}

// 数据懒加载
export const useLazyData = (fn) => {
  const target = ref(null)
  const list = ref([])
  const { stop } = useIntersectionObserver(
    target,
    ([{ isIntersecting }], observerElement) => {
      if (isIntersecting) {
        stop()
        fn().then(res => {
          list.value = res.result
        })
      }
    },
    {
      threshold: 0
    }
  )
  return { target, list }
}

// 封装验证码倒计时
export const useCount = () => {
  const time = ref(0)
  const { pause, resume } = useIntervalFn(() => {
    // console.log('1')
    time.value--
    if (time.value === 0) {
      pause()
    }
  }, 1000, { immediate: false })

  const start = () => {
    time.value = 60
    resume()
  }

  onBeforeUnmount(() => {
    pause()
  })
  return { time, start }
}
